package com.itheima.reflectdemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectDemo3 {

    public static void main(String[] args) throws NoSuchMethodException, NoSuchFieldException, InvocationTargetException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        // 构造器的使用
        Constructor constructor = Student.class.getConstructor();
        // 如果是私有的构造器，可以暴力访问，零时变成公有的
        constructor.setAccessible(true);
        Student student = (Student) constructor.newInstance();
        System.out.println(student);

        System.out.println("----------------------------");
        // 成员变量的使用
        Student student1 = new Student("张三", 18);
        Field field = Student.class.getDeclaredField("name");
        // 暴力访问，零时变成公有的
        field.setAccessible(true);
        field.set(student1, "李四"); // student1.name = "李四";
        System.out.println(student1);
        System.out.println(field.get(student1)); // student1.name

        System.out.println("----------------------------");
        // 成员方法的使用
        Student student2 = new Student("张三", 18);
        Method method = Student.class.getDeclaredMethod("getName");

        method.setAccessible(true);
        System.out.println(method.invoke(student2)); // student2.getName()，如果有参数，则直接将参数放在后续参数里


    }
}
